package edu.ptu.zhiyan.service.comment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ptu.zhiyan.entity.Answer;
import edu.ptu.zhiyan.entity.Comment;
import edu.ptu.zhiyan.mapper.AnswerMapper;
import edu.ptu.zhiyan.mapper.CommentMapper;
import edu.ptu.zhiyan.mapper.QuestionMapper;
import edu.ptu.zhiyan.service.answer.impl.AnswerServiceImpl;
import edu.ptu.zhiyan.service.question.impl.QuestionServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author shengxiao
 * @date 2021/5/21 23:32
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper,Comment> implements IService<Comment> {

    @Resource
    private CommentMapper commentMapper ;

    @Resource
    private AnswerServiceImpl answerServiceImpl ;

    // 添加评论
    public boolean saveComment(Comment comment){

        comment.setTimestamp(new Date());
        int result = commentMapper.insert(comment) ;
        return result == 1 ? true : false ;
    }

    // 获取评论列表
    public List<Comment> queryComments(Integer aid){

        return commentMapper.selectList(new QueryWrapper<Comment>().eq(Comment.AID, aid)) ;
    }

    // 删除评论
    public boolean deleteComment(Integer qid,Integer uid){

        List<Answer> answerList = answerServiceImpl.queryAnswer(qid) ;

        for(int i = 0 ; i < answerList.size() ; i++){
            Answer tmp = answerList.get(i) ;
            if(tmp.getQid()== qid && tmp.getUid() == uid){
                commentMapper.delete(new QueryWrapper<Comment>().eq(tmp.getQid().toString(),qid)
                                                                .eq(Comment.UID, uid)) ;
                return true ;
            }else{
                continue ;
            }
        }

        return false ;

    }

    // 添加评论的点赞
    // 添加点赞
    public boolean insertCThumb(Integer cid){

//        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>() ;
//        String sql = "select thumb from answer where aid = "
//        queryWrapper.exists;
        // 自定义sql语句的更新方式

        try {
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>() ;
            queryWrapper.eq(Comment.CID, cid) ;
            Comment comment = commentMapper.selectOne(queryWrapper) ;

            comment.setThumb(comment.getThumb() + 1);
            UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>() ;
            updateWrapper.eq(Comment.CID,cid) ;
            commentMapper.update(comment, updateWrapper) ;

            return true ;
        } catch (Exception e) {
            return false ;
        }
    }
}
